package com.i2works.smartluolong.utils.ibeetl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * shiro工具类
 *
 * @author koal <koal@vip.qq.com>
 * @date 2017/3/22 15:22
 */
public class ShiroHelper {

    private final static Logger log = LoggerFactory.getLogger(ShiroHelper.class);

    @Resource
    private static SessionDAO sessionDAO;


    //获取所有在线用户
    public static List<JSONObject> getOnlineUser() {
        List<JSONObject> list = Lists.newArrayList();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        if (null != sessions && sessions.size() > 0) {
            System.out.println("共计登录用户：" + sessions.size() + "个");
            for (Session session : sessions) {
                System.out.println("登录ip:" + session.getHost());
                System.out.println("登录用户" + session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
                System.out.println("最后操作日期:" + session.getLastAccessTime());
                JSONObject json = new JSONObject();
                json.put("ip", session.getHost());
                json.put("userName", session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
                json.put("time", session.getLastAccessTime());
                list.add(json);
            }
        } else {
            System.out.println("session为空！");
        }
        return list;
    }

}
